import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, asyncRoutes, constantRoutes, anyRoutes } from '@/router'
import router from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    // 菜单标记:
    routes: [],
    roles: [],
    buttons: [],
    // 根据用户信息筛选后需要展示的异步路由
    resultAsyncRoutes: [],
    // 用户最终需要展示的全部路由
    resultAllRoutes: []
  }
}

// 对比本地异步路由和后端返回的异步路由，筛选得出当前用户所能访问的异步路由
const computedAsyncRoutes = (asyncRoutes, routes) => {
  // 过滤当前用户
  return asyncRoutes.filter(item => {
    // console.log(item)
    // 判断routes中有没有asyncRoutes中的路由名称
    if (routes.indexOf(item.name) != -1) {
      // 递归遍历深层次路由
      if (item.children && item.children.length) {
        item.children = computedAsyncRoutes(item.children, routes)
      }
      return true
    }
  })
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userData) => {
    // 用户名
    state.name = userData.name
    // 用户头像
    state.avatar = userData.avatar
    // 按钮权限标记
    state.buttons = userData.buttons
    // 菜单权限标记
    state.routes = userData.routes
    // 角色
    state.roles = userData.roles
  },
  // 最终筛选出的异步路由
  SET_RESULTASYNCROUTES: (state, asyncRoutes) => {
    // vuex中存放用户的异步路由
    state.resultAsyncRoutes = asyncRoutes
    // 合并当前用户需要展示的全部路由
    state.resultAllRoutes = constantRoutes.concat(state.resultAsyncRoutes, anyRoutes)
    // 添加新的异步路由
    router.addRoutes(state.resultAsyncRoutes)
  }
}

const actions = {
  // user login
  async login ({ commit }, userInfo) {
    const { username, password } = userInfo
    // async/await写法
    const result = await login({ username: username.trim(), password: password })
    // console.log(result)
    if (result.code === 20000) {
      commit('SET_TOKEN', result.data.token)
      // 若获取到token,在cookie中存一份
      setToken(result.data.token)
    } else {
      // 响应失败
      return Promise.reject(new Error('fail'))
    }
    // 旧promise写法
    // return new Promise((resolve, reject) => {
    //   login({ username: username.trim(), password: password }).then(response => {
    //     const { data } = response
    //     commit('SET_TOKEN', data.token)
    //     setToken(data.token)
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // get user info
  async getUserInfo ({ commit, state }) {
    let result = await getInfo(state.token)
    console.log(result)
    if (result.code === 20000) {
      const data = result.data
      if (!data) {
        return Promise.reject('Verification failed, please Login again.')
      }
      // vuex存储用户信息
      commit('SET_USERINFO', data)
      commit('SET_RESULTASYNCROUTES', computedAsyncRoutes(asyncRoutes, data.routes))
      return 'ok'
    }
  },
  // getInfo ({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response
  //       // console.log(data)
  //       // console.log(state)

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }
  //       // vuex存储用户信息
  //       commit('SET_USERINFO', data)
  //       commit('SET_RESULTASYNCROUTES', computedAsyncRoutes(asyncRoutes, data.routes))
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error.message)
  //     })
  //   })
  // },

  // user logout
  logout ({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

